package com.gcsoftware.authentications.helper;

import com.gcsoftware.authentications.beans.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;

/**
 * Created by qs on 2018/3/15.
 */
public class ShiroUtils {
    /**  加密算法 */
    public final static String HASH_ALGORITHM_NAME = "SHA-256";
    /**  循环次数 */
    public final static int HASH_ITERATIONS = 16;

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static <T> T getSessionAttribute(Object key) {
        return (T) getSession().getAttribute(key);
    }

    public static UserInfo getUserInfo() {
        return (UserInfo) getSession().getAttribute("user");
    }
    public static String sha256(String password, String salt) {
        return new SimpleHash(HASH_ALGORITHM_NAME, password, salt, HASH_ITERATIONS).toString();
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if(kaptcha == null){
            throw new RuntimeException("验证码已失效");
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }
}
